package cn.iocoder.yudao.module.infra.framework.encrypt;

import cn.hutool.core.util.StrUtil;
import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
@EnableEncryptableProperties
@Slf4j
public class JasyptConfig {

    @Bean(name = "jasyptStringEncryptor")
    public StringEncryptor stringEncryptor(Environment environment) {
        final String password = getPassword(environment);
        final StringEncryptor encryptor = JasyptUtils.getPooledPBEStringEncryptor(password);
        return encryptor;
    }

    private static String getPassword(Environment environment) {
        String password = environment.getProperty("jasypt.encryptor.password");
        if (StrUtil.isEmpty(password)) {
            password = environment.getProperty("jasypt.encryptor.default-password");
            if (StrUtil.isNotEmpty(password)) {
                log.info("配置文件value密码来源-default-password");
            }
        } else {
            log.info("配置文件value密码来源-password");
        }

        if (StrUtil.isEmpty(password)) {
            throw new IllegalArgumentException("jasypt.encryptor.password 未配置");
        }
        return password;
    }

}
